/**
 * 
 */
package cn.edu.cqu.bysj.wm.ago.gn;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;

import cn.edu.cqu.bysj.wm.def.PropertyDef;
import cn.edu.cqu.bysj.wm.util.NodeComparator;

/**
 * @author Meng
 * 
 */
public class GNCommunity {

	public static HierarchyTree hTree;

	// map of community id and nodes
	public static Map<Long, List<Node>> communitys;

	// map of community size and community number
	public static Map<Integer, Integer> cscn;

	private static long CID;

	/**
	 * according to the whole htree to show all communitys
	 * 
	 * @param tree
	 */
	public static void showCommunity(HierarchyTree tree) {

		hTree = tree;
		communitys = hTree.communitys;

		for (long id : hTree.communitys.keySet()) {
			List<Node> list = hTree.communitys.get(id);
			Collections.sort(list, new NodeComparator());
		}
	}

	/**
	 * fill a leaf node to htree after success of judge partition
	 * 
	 * @param list
	 *            node list
	 * @param gdb
	 *            graph database service
	 * @param tree
	 *            hierarchy tree
	 * 
	 */
	public static void fillHierarchyTree(List<Node> list,
			GraphDatabaseService gdb, HierarchyTree tree) {

		Transaction tx = gdb.beginTx();
		try {
			long pid = (Long) list.iterator().next()
					.getProperty(PropertyDef.COMMUNITY_ID);

			CID = tree.addChild(pid, list);

			for (Node node : list) {
				node.setProperty(PropertyDef.COMMUNITY_ID, CID);
			}

			tx.success();
		} finally {
			tx.finish();
		}
	}

	/**
	 * fill the map of cscn
	 * 
	 * @param communitys
	 */
	public static void sizeNumber(Map<Long, List<Node>> communitys) {

		cscn = new HashMap<Integer, Integer>();

		for (long i : communitys.keySet()) {
			int size = communitys.get(i).size();
			if (cscn.containsKey(size)) {
				cscn.put(size, cscn.get(size) + 1);
			} else {
				cscn.put(size, 1);
			}
		}
	}
}
